package com.itjob.deep.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.itjob.deep.bean.TalkBean;
import com.itjob.deep.bean.UserBean;

public class RefreshServlet extends HttpServlet {
	
	private static final long serialVersionUID = -6505644331689498222L;

	private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

	@Override
	@SuppressWarnings("unchecked")
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext application = this.getServletContext();
		HttpSession session = request.getSession();
		UserBean user = (UserBean) session.getAttribute("user");
		
		StringBuffer buffer = new StringBuffer("{");
		Map<String, UserBean> users = (Map<String, UserBean>) application.getAttribute("users");
		
		buffer.append("count:" + (users == null ? 0 : users.size()));
		
		if (users != null) {
			buffer.append(",staff:[");
			for (UserBean bean : users.values()) {
				buffer.append("{");
				
				buffer.append("username");
				buffer.append(":");
				buffer.append("\"");
				buffer.append(bean.getUsername());
				buffer.append("\",");
				
				buffer.append("gender");
				buffer.append(":");
				buffer.append("\"");
				buffer.append(bean.getGender());
				buffer.append("\"");
				
				buffer.append("}");
				buffer.append(",");
			}
			
			buffer.delete(buffer.length() - 1, buffer.length());
			buffer.append("]");
		}
		
		List<TalkBean> talks = (List<TalkBean>) application.getAttribute("talks");
		if (talks != null) {
			
			if (talks.size() > 100) {
				for (int i = 0; i < 20; i++) {
					talks.remove(0);
				}
			}
			
			buffer.append(",talks:\"");
			for (TalkBean tb : talks) {
				
				// 过滤掉登录前的聊天记录
				if (user.getLoginTime() > tb.getSendTime()) {
					continue;
				}
				
				// 拼时间
				buffer.append("[");
				buffer.append(sdf.format(new Date(tb.getSendTime())));
				buffer.append("] ");
				
				// 拼姓名
				buffer.append(tb.getUsername());
				buffer.append(" : ");
				
				// 拼内容
				buffer.append(tb.getSaid());
				
				// 拼回车换行
				buffer.append("<br>");
			}
			
			buffer.append("\"");
		}
		
		buffer.append("}");
		
		//System.out.println(buffer.toString());
		response.setCharacterEncoding("UTF-8");
		
		PrintWriter writer = response.getWriter();
		writer.write(buffer.toString());
		writer.flush();
		writer.close();
	}
}
